package com.neuedu.his.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neuedu.his.po.Constantitem;
import com.neuedu.his.po.Invoice;
import com.neuedu.his.po.Register;
import com.neuedu.his.service.ConstantitemService;
import com.neuedu.his.service.InvoiceService;
import com.neuedu.his.service.RegistlevelService;
import com.neuedu.his.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

@RestController
@RequestMapping("/api/master/register")
public class RegisterController {

    @Autowired
    private RegisterService registerService;

    @Autowired
    private RegistlevelService registLevelService;

    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private ConstantitemService constantItemService;

    /**
     * 收费方式列表，只返回 ConstantTypeID=5 的项目
     */
    @GetMapping("/feeTypes")
    public ResponseEntity<List<Constantitem>> feeTypes() {
        List<Constantitem> list = constantItemService.list(
                new QueryWrapper<Constantitem>()
                        .eq("ConstantTypeID", 5)
                        .eq("DelMark", 1)
        );
        return ResponseEntity.ok(list);
    }

    /**
     * 计算应收金额 = 挂号费 +（选病历本 ? 1 : 0）
     */
    @GetMapping("/calcAmount")
    public ResponseEntity<Map<String, BigDecimal>> calcAmount(
            @RequestParam Integer registleid,
            @RequestParam String isbook) {
        BigDecimal base = registLevelService.getById(registleid).getRegistfee();
        BigDecimal book = "Y".equalsIgnoreCase(isbook) ? BigDecimal.ONE : BigDecimal.ZERO;
        return ResponseEntity.ok(Collections.singletonMap("amount", base.add(book)));
    }

    /**
     * 查询剩余号额（支持午别，但限额表当前未区分）
     */
    @GetMapping("/getQuota")
    public ResponseEntity<Map<String, Integer>> getQuota(
            @RequestParam Integer registleid,
            @RequestParam(required = false) String noon) {
        Integer quota = registLevelService.getById(registleid).getRegistquota();
        return ResponseEntity.ok(Collections.singletonMap("quota", quota));
    }

    /**
     * 现场挂号
     * - 保存 Register（生成病历号）
     * - 扣减号额
     * - 生成发票 Stub
     * @param register 前端表单传来的 Register 对象
     * @param userId   从 X-User-Id header 获取的当前登录用户 ID
     */
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Map<String, Object>> create(
            @RequestBody Register register,
            @RequestHeader("X-User-Id") Integer userId
    ) {
        Date now = new Date();
        String caseNo = new SimpleDateFormat("yyyyMMddHHmmss").format(now);
        register.setCasenumber(caseNo);
        register.setVisitdate(now);
        register.setRegisttime(now);

        String noonVal = register.getNoon();
        if (noonVal == null || noonVal.isBlank()) {
            noonVal = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) < 12 ? "上午" : "下午";
        }
        register.setNoon(noonVal);

        register.setRegisterid(userId);
        register.setVisitstate(1);
        registerService.save(register);

        // 扣减限额
        var level = registLevelService.getById(register.getRegistleid());
        level.setRegistquota(level.getRegistquota() - 1);
        registLevelService.updateById(level);

        // 生成发票 Stub
        String invoiceNo = "INV"
                + new SimpleDateFormat("yyyyMMddHHmmss").format(now)
                + String.format("%04d", new Random().nextInt(10000));
        Invoice stub = new Invoice();
        stub.setRegistid(register.getId());
        stub.setInvoicenum(invoiceNo);
        stub.setState(0);
        stub.setDailystate(0);
        stub.setMoney(BigDecimal.ZERO);
        stub.setCreationtime(now);
        stub.setUserid(userId);
        invoiceService.save(stub);

        Map<String, Object> resp = new HashMap<>();
        resp.put("id", register.getId());
        resp.put("casenumber", caseNo);
        resp.put("invoicenum", invoiceNo);
        return ResponseEntity.ok(resp);
    }

    /**
     * 缴费接口
     * @param body   包含 registId 和 amount
     * @param userId 从 X-User-Id header 获取的当前登录用户 ID
     */
    @PostMapping("/pay")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Map<String, String>> pay(
            @RequestBody Map<String, Object> body,
            @RequestHeader("X-User-Id") Integer userId
    ) {
        Integer registId  = Integer.parseInt(body.get("registId").toString());
        BigDecimal amount = new BigDecimal(body.get("amount").toString());

        Invoice inv = invoiceService.getOne(
                new QueryWrapper<Invoice>()
                        .eq("RegistID", registId)
                        .eq("State", 0)
                        .orderByDesc("CreationTime")
                        .last("LIMIT 1")
        );
        if (inv == null) {
            return ResponseEntity.status(404)
                    .body(Collections.singletonMap("error", "未找到可缴费发票"));
        }

        inv.setMoney(amount);
        inv.setUserid(userId);
        inv.setCreationtime(new Date());
        inv.setState(1);
        invoiceService.updateById(inv);

        Register upd = new Register();
        upd.setId(registId);
        upd.setVisitstate(2);
        registerService.updateById(upd);

        return ResponseEntity.ok(Collections.singletonMap("status", "paid"));
    }

    /**
     * 获取最新发票详情，用于打印
     */
    @GetMapping("/receipt")
    public ResponseEntity<Invoice> receipt(@RequestParam Integer registId) {
        Invoice inv = invoiceService.getOne(
                new QueryWrapper<Invoice>()
                        .eq("RegistID", registId)
                        .orderByDesc("CreationTime")
                        .last("LIMIT 1")
        );
        return inv == null
                ? ResponseEntity.status(404).build()
                : ResponseEntity.ok(inv);
    }

    /**
     * 医生端当日未缴费挂号列表
     */
    @GetMapping("/list")
    public ResponseEntity<Page<Register>> list(
            @RequestParam Integer userid,
            @RequestParam(defaultValue = "1") long page,
            @RequestParam(defaultValue = "20") long pageSize
    ) {
        LocalDate today = LocalDate.now();
        Date start = Date.from(today.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date end   = Date.from(today.plusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant());
        QueryWrapper<Register> q = new QueryWrapper<Register>()
                .eq("UserID", userid)
                .eq("VisitState", 1)
                .between("VisitDate", start, end)
                .orderByAsc("RegistTime");
        Page<Register> result = registerService.page(new Page<>(page, pageSize), q);
        return ResponseEntity.ok(result);
    }
}
